﻿<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8" />
  <script src="./js/vue.js"></script>
  <style>
    td{
      width:40px;
      height:40px;
      border: 1px solid black;
    }
    .red{
      background-color:red;
      pointer-events:none;
    }
    .green{
      background-color:green;
      pointer-events:none;
    }
  </style>
</head>
<body>
<div id="panel">
  <button v-show="user==0" @click="init(1)">红子</button>
  <button v-show="user==0" @click="init(-1)">绿子</button>
  <table :style="isBoardClick?'':'pointer-events:none'">
    <tr v-for="row,i in board">
      <td v-for="col,j in row" @click="setValue(i,j,user)" :class="col==1?'red':(col==-1?'green':'')">{{col}}</td>
    </tr></table>
</div>
<script>
  var ajax = new XMLHttpRequest();
  var panel = new Vue({
    el:"#panel",
    data:{
      user:0,
      isBoardClick:false,
      pollingTarget:'http://127.0.0.1:8888/PollingHandler?user=',
      updateTarget:'http://127.0.0.1:8888/UpdateHandler?user=',
      board:[[0,1,1,0],[0,0,1,0],[0,1,0,0],[0,1,1,0]]
    },
    methods:{
      init:function(user){
        this.user = user;
        if(user == 1){ //先手,直接解锁点击
          this.isBoardClick = true;
        }
      },
      setValue:function(i,j,value){
        Vue.set(this.board[i],j,value);
        this.isBoardClick = false;
        //去子，数据更新
        ajax.open('get',this.updateTarget+(value*-1)+'&board='+JSON.stringify(this.board),true);
        ajax.send();
      }
    }
  });
  ajax.onreadystatechange = function(){ //获得响应
    if(ajax.readyState === XMLHttpRequest.DONE && ajax.status === 200) {
      if(ajax.responseText != ''){ //不是发送更新数据请求
        panel.board = eval(JSON.parse(ajax.responseText));
        panel.isBoardClick = true;
      }
    }
  }
  var polling = function(){
    if(panel.user != 0){ //需要用户初始化角色完成方可轮询
      ajax.open('GET',panel.pollingTarget+panel.user,true);
      ajax.send();
    }
  };
  setInterval(polling,1000);
</script>
</body>
</html>